package CompletableFuture.电商比价;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @program: algorithm
 * @description: 电商比价demo
 * @author: 陈恩涛
 * @create: 2022-08-09 22:42
 **/
public class CompletableFutureMallDemo {

     static List<NetMall> netMalls = Arrays.asList(
                new NetMall("jd", 101),
                new NetMall("taobao", 99),
                new NetMall("dangadang", 88)
        );


    private static List<String> getPrice(List<NetMall> list) {
        return list.stream().map(netMall ->
            String.format("mysql in %s price is %.2f", netMall.getName(), netMall.getPrice()))
                .collect(Collectors.toList());
    }

    private static List<String> getPriceCf(List<NetMall> list) {
        return list.stream().map(netMall ->
                CompletableFuture.supplyAsync(() ->
                        String.format("mysql in %s price is %.2f", netMall.getName(), netMall.getPrice())))
                .collect(Collectors.toList())
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        getPrice(netMalls).forEach(System.out::println);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - begin));

        begin = System.currentTimeMillis();
        getPriceCf(netMalls).forEach(System.out::println);
        end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - begin));
    }

}

class NetMall{

    private String name;

    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public NetMall(String name, double price) {
        this.name = name;
        this.price = price;
    }
}
